package com.minimoment.base;

import com.minimoment.model.domain.Screenings;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by etund on 2014/10/30.
 */
@Transactional
@SuppressWarnings("all")
public abstract class BaseSupportImpl<T> implements BaseSupport<T> {
    /**
     *
     */
    protected  List<T> list = new ArrayList<T>();
    @Resource(name = "sessionFactory")
    public SessionFactory sessionFactory;

    protected  Class<T> clazz;

    public BaseSupportImpl() {
        ParameterizedType pt = (ParameterizedType)this.getClass().getGenericSuperclass();
        this.clazz = (Class<T>)pt.getActualTypeArguments()[0];
        System.out.println("clazz==========="+clazz);
    }

    public Session getSession(){
        return  sessionFactory.getCurrentSession();
    }


    @Override
    public void save(T t) {
        getSession().save(t);
    }

    @Override
    public void del(Long id) {
        if(id==null){
            return;
        }
        Object entity = getById(id);
        if(entity==null){
            return;
        }
        getSession().delete(entity);
    }

    @Override
    public void update(T t) {
        getSession().update(t);
    }

    @Override
    public T getById(Long id) {
        if(id==null)
            return null;
        return (T)getSession().get(clazz,id);

    }

    @Override
    public List<T> findByIds(Long[] ids) {
        if(ids==null)
            return null;

        /**
         * // 注意空格！
         "FROM " + clazz.getSimpleName() + " WHERE id IN (:ids)")//
         .setParameterList("ids", ids)// 注意一定要使用setParameterList()方法！
         .list();
         */
        return getSession().createQuery("from "+clazz.getSimpleName()+" where id in(:ids)").setParameterList("ids",ids).list();
    }

    @Override
    public List<T> findAll() {

        list = getSession().createQuery("from " +clazz.getSimpleName()).list();
        return list;
    }

}
